import { reqCartList, reqDeleteCartShop, reqShopChecked } from "@/api"
const state = {
  cartList:[]
}
const mutations = {
  GETCRTLIST(state,cartList){
    state.cartList = cartList
  }
}
const actions = {
  // 获取购物车数据
  async getCartList({commit}){
    let res = await reqCartList()
    // console.log(res)
    if(res.data.code === 200){
      commit('GETCRTLIST',res.data.data)
    }
  },
  // 删除购物车商品
  async deleteCartShop({commit},skuId){
    let res = await reqDeleteCartShop(skuId)
    if(res.data.code===200){
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车商品选中状态
  async shopChecked({commit},{skuId,isChecked}){
    let res = await reqShopChecked(skuId,isChecked)
    if(res.data.code===200){
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除选中的所有商品
  deleteAllCartShop({dispatch,getters}){
    // console.log(context)
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('deleteCartShop',item.skuId) : ''
      // 将每一次的promise添加到数组中
      PromiseAll.push(promise)
    });
    return Promise.all(PromiseAll)
  },
  // 修改全选，反选状态
  isAllChecked({dispatch,state},isChecked){
    // console.log(state)
    // console.log(isChecked)
    let promiseAll = []
    if(state.cartList[0]){

      state.cartList[0].cartInfoList.forEach(item=>{
        let promise = dispatch('shopChecked',{skuId:item.skuId,isChecked})
        promiseAll.push(promise)
      })
    }
    return Promise.all(promiseAll)
  }
}
const getters = {
  cartList(state){
    return state.cartList[0] || {}
  }
}
export default{
  state,
  mutations,
  actions,
  getters
}